<?php

namespace app\api\controller;

// 如果场景需要用到用户必须登录的话则继承这个
class AuthBase extends ApiBase
{
    public $accessToken = '';
    public $id = '';
    public $username = '';

    public function initialize()
    {
        parent::initialize();
        // 获取header传递过来的access-key,而这个key则是存储在redis中的缓存名称
        $this->accessToken = request()->header('access-token');
        // dump($this->accessToken);
        if (!$this->accessToken || !$this->isLogin()) {
            return $this->show(config('status.error'), '没有登录！');
        }
    }

    public function isLogin()
    {
        $userInfo = cache(config('redis.token_pre') . $this->accessToken);
        if (empty($userInfo)) {
            return false;
        }

        // 判断userInfo中的id和username是否存在值
        if (!empty($userInfo['id']) && !empty($userInfo['username'])) {
            $this->username = $userInfo['username'];
            $this->id = $userInfo['id'];
            return true;
        }
        return false;
    }
}
